package com.xjl.example.atomic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicExample4 {

    private static Logger logger = LoggerFactory.getLogger(AtomicExample4.class);

      final static int totalCount = 5000;
      final static int threadCount = 200;

    static AtomicInteger atomicInteger = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        final Semaphore semaphore = new Semaphore(threadCount);
        final CountDownLatch countDownLatch = new CountDownLatch(totalCount);
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i <totalCount; i++) {
           service.execute(() ->{

               try {
                   semaphore.acquire();
                   add();
                   semaphore.release();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               countDownLatch.countDown();
           });
        }

        countDownLatch.await();
       service.shutdown();
        logger.info(String.valueOf(atomicInteger.get()));
    }

    private static void add() {
        atomicInteger.incrementAndGet();
    }
}
